using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.ProcessManagement;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ProcessManagements;

namespace RBAC.Write.Api.Application.Handler.ProcessManagements
{
    /// <summary>
    /// 批量删除工序分类 处理器（逻辑删除）
    /// </summary>
    public class BatchDeleteProcessClassificationsHandler : IRequestHandler<BatchDeleteProcessClassificationsCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ProcessClassification> repository;
        private readonly ILogger<BatchDeleteProcessClassificationsHandler> logger;

        public BatchDeleteProcessClassificationsHandler(
            IBaseRepository<ProcessClassification> repository,
            ILogger<BatchDeleteProcessClassificationsHandler> logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(BatchDeleteProcessClassificationsCommand request, CancellationToken cancellationToken)
        {
            var res = new APIResult<int>();
            try
            {
                if (request.Ids == null || request.Ids.Count == 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "请选择要删除的记录";
                    return Task.FromResult(res);
                }

                // 逻辑删除
                var sql = "UPDATE ProcessClassification SET IsDeleted=1 WHERE Id IN @Ids AND IsDeleted=0";
                var rows = repository.Execute(sql, new { request.Ids });

                res.Code = APIEnums.Success;
                res.Data = rows;
                res.Msg = rows > 0 ? "删除成功" : "未删除任何记录";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "批量删除工序分类失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "批量删除异常";
                res.Data = 0;
            }

            return Task.FromResult(res);
        }
    }
}
